import csv
import time
from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Edge()
driver.get("https://www.jd.com/")
driver.find_element(By.CSS_SELECTOR, "#key").send_keys("电脑笔记本")
driver.find_element(By.CSS_SELECTOR, "#search > div > div.form > button > i").click()
time.sleep(5)

mydicyheader = ["电脑名字", "电脑简介", "电脑价格", "电脑评价", "电脑商铺", "电脑状态"]
with open("D:/JetBrains Projects/Pycharm Projects/python-learn/爬虫作业/京东商品/京东电脑笔记本.csv", "a", encoding="UTF-8", newline="") as f:
    dictwriter = csv.DictWriter(f, mydicyheader)
    dictwriter.writeheader()
    for i in range(5):
        mylist = driver.find_elements(By.CSS_SELECTOR, "li")
        for li in mylist:
            try:
                mydict = {
                    "电脑名字": li.find_element(By.CSS_SELECTOR, ".p-name em").text.replace("\n", " "),
                    "电脑简介": li.find_element(By.CSS_SELECTOR, ".p-name a").get_attribute("title").replace("\n", " "),
                    "电脑价格": li.find_element(By.CSS_SELECTOR, ".p-price strong").text,
                    "电脑评价": li.find_element(By.CSS_SELECTOR, ".p-commit strong").text,
                    "电脑商铺": li.find_element(By.CSS_SELECTOR, ".J_im_icon a").text,
                    "电脑状态": li.find_element(By.CSS_SELECTOR, ".p-icons").text.replace("\n", "，")
                }
                dictwriter.writerow(mydict)
            except:
                pass
        driver.find_element(By.CSS_SELECTOR, "#J_bottomPage > span.p-num > a.pn-next > i").click()
        time.sleep(5)
